package cn.oniokey.waterDetection.controller;

import cn.oniokey.waterDetection.domain.Water;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@Service
public class MqttController {

    private MqttClient mqttClient;

    final
    InsertWaterController insertWaterController;

    public MqttController(InsertWaterController insertWaterController) {
        this.insertWaterController = insertWaterController;
            // 写死配置信息!!!
        try {
            // mqtt 的请求地址
            String broker = "tcp://post-cn-jia3oay1m01.mqtt.aliyuncs.com:1883";
            // mqtt 的客户端id
            String clientId = "GID_Test@@@zw.zhou";
            // 新建 mqtt 的客户端
            mqttClient = new MqttClient(broker, clientId);
            // 新建 mqtt 连接
            MqttConnectOptions options = new MqttConnectOptions();
            // 设置 mqtt 的连接用户名
            options.setUserName("Signature|LTAI5tPnR3dJmNWFpHPtFJxe|post-cn-jia3oay1m01");
            // 设置 mqtt 的连接密码
            options.setPassword("EmnT4P/bJD3+lS8nRgyajAxyNR0=".toCharArray());
            // mqtt 客户端连接到 mqtt 服务端
            mqttClient.connect(options);
            // mqtt 的订阅主题
            subscribe("test");
            // 日志记录连接信息
            if (mqttClient.isConnected()) {
                log.info("MQTT连接成功!!!");
            } else {
                log.info("MQTT连接失败!!!");
            }
        } catch (MqttException e) {
            log.info("MQTT连接异常:" + e.getMessage());
        }
    }

    public void subscribe(String topic) {
        try {
            mqttClient.subscribe(topic);
            mqttClient.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    // 连接丢失后尝试重新连接
                    log.info("连接丢失,正在尝试重新连接...");
                    try {
                        mqttClient.reconnect();
                    } catch (MqttException e) {
                        log.info("重新连接失败:" + e.getMessage());
                    }
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) {
                    // 输出 mqtt 客户端收到的消息
                    log.info("Received message:" + new String(message.getPayload()));
                    // 使用 Jackson 解析 JSON 数据并封装到 Water 对象中
                    ObjectMapper objectMapper = new ObjectMapper();
                    try {
                        Water water = objectMapper.readValue(message.getPayload(), Water.class);
                        // 调用 InsertWaterController 的 insertWater 方法
                        insertWaterController.insertWater(water);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    // 消息发送成功后的回调
                }

            });
            log.info("成功订阅主题:" + topic);
        } catch (MqttException e) {
            log.info("订阅主题失败:" + e.getMessage());
        }
    }
}


